#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define PORT 7000
#define QUEUE   20
#define BUFFER_SIZE 1024

int main()
{
	int server_sock,client_sock;		/*ss为服务器的socket描述符，sc为客户端的socket描述符*/
	struct sockaddr_in server_address;	/*服务器地址结构*/
	struct sockaddr_in client_address;	/*客户端地址结构*/
	pid_t pid;
	
    server_sock = socket(PF_INET, SOCK_STREAM, 0);
	
	bzero(&server_address, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr =htonl(INADDR_ANY);
    server_address.sin_port = htons(PORT);
	
    if(bind(server_sock, (struct sockaddr *)&server_address, sizeof(server_address)) == -1)
	{
		printf("bind error");
		exit(1);
	}

    if(listen(server_sock, QUEUE) == -1)
	{
		printf("listen error");
		exit(1);
	}
    
    /* 接受连接 */
	while(1)
	{
		int client_len = sizeof(client_address);
		client_sock = accept(server_sock, (struct sockaddr *)&client_address, &client_len);
		if(client_sock < 0)
		{
			continue;
		}
			pid = fork();
		if(pid == 0){//子进程
		
			char buffer[BUFFER_SIZE];						/*数据的缓冲区*/
			while(1){									/*循环处理过程*/		
			   ssize_t size = recv(client_sock, buffer, sizeof(buffer),0);			/*从套接字中读取数据放到													缓冲区buffer中*/
				if(strcmp(buffer,"exit\n")==0)
					break;
				fputs(buffer, stdout);
				send(client_sock, buffer, size, 0);
			}	
			close(server_sock);
			exit(0);
		}else{//父进程
			close(client_sock);
		}
	}
}

